package com.cssw.fyzb.tps.service.auth.tecent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cssw.fyzb.tps.exception.BizException;
import com.cssw.fyzb.tps.util.HttpUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import static com.cssw.fyzb.tps.util.Bizs.USER_AUTH_INFO_SEND_FAIL;

/**
 * @Author zhouxu
 * @create 2020-09-14 21:30
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class UserAuthInfo {

    private static final Logger logger = LoggerFactory.getLogger(UserAuthInfo.class);


    private String url;

    private String webankAppId;

    /**
     * 比对源照片，注意：原始图片不能超过 500k，且必须为 JPG 或 PNG 格式。
     * 参数有值：使用合作伙伴提供的比对源照片进行比对，必须注照片是正脸可信照片，照片质量由合作方保证。
     * 参数为空 ：根据身份证号 + 姓名使用权威数据源比对
     */
    private String sourcePhotoStr;

    private String license;

    /**
     * 比对源照片类型，参数值为1 时是：水纹正脸照。参数值为 2 时是：高清正脸照
     */
    private String sourcePhotoType;

    /**
     * 默认参数值为：1.0.0
     */
    private String version;

    /**
     * 签名：wbappid,userId,nonceStr,version,ticket 字典排序,计算 SHA1 得到签名（40位），不区分大小写。
     */
    private String sign;

    /**
     * 必须是32位随机数
     */
    private String nonceStr;

    /**
     * 合作伙伴服务端缓存的 ticket，注意是 NONCE 类型
     */
    private String ticket;

    public HttpResult sendUserInfo(String userId, String name, String idNo, String nonceStr, String orderNo, String ticketValue, String sign) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("webankAppId", webankAppId);
        param.put("sourcePhotoStr", sourcePhotoStr);
        param.put("sourcePhotoType", sourcePhotoType);
        param.put("version", version);
        param.put("nonceStr", nonceStr);
        param.put("orderNo", orderNo);
        param.put("name", name);
        param.put("idNo", idNo);
        param.put("userId", userId);
        param.put("ticket", ticketValue);
        param.put("sign", sign);

        logger.debug("合作方后台上送身份信息入参：" + JSON.toJSONString(param));

        long startTime = System.currentTimeMillis();
        String json = HttpUtil.post(url, JSONObject.toJSONString(param));
        logger.debug("合作方后台上送身份信息返回：" + json);
        long endTime = System.currentTimeMillis();
        logger.debug("useTime: " + (endTime - startTime));

        HttpResult result = parseJson(json);
        if (result == null || !HttpResult.STATUS_SUCCESS.equals(result.code)) {
            logger.error(json);
            String errmsg = null;
            if (result != null)
                errmsg = result.getMsg();
            throw new BizException(USER_AUTH_INFO_SEND_FAIL.code, USER_AUTH_INFO_SEND_FAIL.message + errmsg);
        }

        return result;

    }

    private HttpResult parseJson(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");

        JSONObject dataObject = jsonObject.getJSONObject("result");
        String bizSeqNo = dataObject.getString("bizSeqNo");
        String orderNo = dataObject.getString("orderNo");
        String faceId = dataObject.getString("faceId");

        Data data = new Data();
        data.setBizSeqNo(bizSeqNo);
        data.setFaceId(faceId);
        data.setOrderNo(orderNo);

        HttpResult result = new HttpResult();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data);

        return result;
    }


    /**
     * 出参报文：
     * {
     * "code": 0,
     * "msg": "成功",
     * "result": {
     * "bizSeqNo":"业务流水号",
     * "orderNo":"合作方订单号",
     * "faceId":"cc1184c3995c71a731357f9812aab988"
     * }
     * }
     */
    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class HttpResult {

        public static final String STATUS_SUCCESS = "0";

        private String msg;
        private boolean success;
        private String code;
        private Data data;

    }

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    private class Data {
        String bizSeqNo;
        String orderNo;
        String faceId;

    }

    public static void main(String[] args) throws Exception {
        String url = "https://idasc.webank.com/api/server/getfaceid";
        String webankAppId = "TIDAD0fb";
        String orderNo = "003bc36b-0907-488b-a34b-52a4b6d1bcf2";
        String name = "张三";
        String idNo = "430426199705017678";
        String userId = "1";
        String sourcePhotoStr = null;
        String sourcePhotoType = "1";
        String version = "1.0.0";
        String sign = "test";
        String nonceStr = "";

        UserAuthInfo userAuthInfo = new UserAuthInfo();
        userAuthInfo.setUrl(url);
        userAuthInfo.setWebankAppId(webankAppId);
        userAuthInfo.setSourcePhotoStr(sourcePhotoStr);
        userAuthInfo.setSourcePhotoType(sourcePhotoType);
        userAuthInfo.setVersion(version);
        userAuthInfo.setSign(sign);

        // NONCETicket
        String ticketValue = "";
        HttpResult result = userAuthInfo.sendUserInfo(userId, name, idNo, nonceStr, orderNo, ticketValue, sign);
        logger.debug(result.toString());

    }

}
